<template>
  <div class="tags-page">
    <!-- 简洁页面头部 -->
    <div class="page-header">
      <div class="header-left">
        <h1>标签管理</h1>
        <span class="total-count">共 {{ tagStore.pagination.total }} 个标签</span>
      </div>
      <div class="header-right">
        <div class="search-container">
          <el-input
            v-model="searchForm.search"
            placeholder="请输入标签名称进行搜索..."
            clearable
            @clear="handleSearch"
            @keyup.enter="handleSearch"
            class="search-input"
            size="large"
          >
            <template #prefix>
              <el-icon class="search-icon"><Search /></el-icon>
            </template>
            <template #append>
              <el-button 
                @click="handleSearch" 
                :loading="tagStore.isLoading"
                type="primary"
                class="search-btn"
              >
                <el-icon><Search /></el-icon>
              </el-button>
            </template>
          </el-input>
        </div>
        <el-button type="primary" @click="openCreateDialog" size="large" class="add-btn">
          <el-icon><Plus /></el-icon>
          添加标签
        </el-button>
      </div>
    </div>

    <!-- 优化表格容器 -->
    <div class="table-container">
      <div class="table-header" v-if="selectedIds.length > 0">
        <div class="table-title">
          <span>已选择 {{ selectedIds.length }} 项</span>
        </div>
        <div class="table-actions">
          <el-button
            type="danger"
            size="small"
            @click="handleBatchDelete"
            class="batch-btn"
          >
            <el-icon><Delete /></el-icon>
            批量删除
          </el-button>
        </div>
      </div>
      
      <div class="table-wrapper">
        <el-table
          :data="tagStore.tags"
          v-loading="tagStore.isLoading"
          @selection-change="handleSelectionChange"
          row-key="id"
          stripe
          height="500"
          :scrollbar-always-on="true"
          class="data-table"
        >
          <el-table-column type="selection" width="50" />
          
          <el-table-column label="序列" width="80" type="index" :index="(index: number) => (searchForm.page - 1) * searchForm.limit + index + 1" />
          
          <el-table-column label="标签名称" min-width="200">
            <template #default="{ row }">
              <div class="tag-info">
                <div 
                  class="tag-color" 
                  :style="{ backgroundColor: row.color || '#409EFF' }"
                ></div>
                <div>
                  <div class="tag-name">{{ row.name }}</div>
                  <div class="tag-slug">{{ row.slug }}</div>
                </div>
              </div>
            </template>
          </el-table-column>
          
          <el-table-column prop="description" label="描述" min-width="200" show-overflow-tooltip>
            <template #default="{ row }">
              {{ row.description || '-' }}
            </template>
          </el-table-column>
          
          <el-table-column label="使用次数" width="100">
            <template #default="{ row }">
              {{ row.lessonCount || 0 }}
            </template>
          </el-table-column>
          
          <el-table-column label="状态" width="80">
            <template #default="{ row }">
              <el-switch
                v-model="row.isActive"
                @change="handleStatusChange(row)"
                size="small"
              />
            </template>
          </el-table-column>
          
          <el-table-column label="创建时间" width="120">
            <template #default="{ row }">
              {{ formatDate(row.createdAt) }}
            </template>
          </el-table-column>
          
          <el-table-column label="操作" width="160" fixed="right">
            <template #default="{ row }">
              <el-button type="primary" link size="small" @click="handleEdit(row)">
                编辑
              </el-button>
              <el-button type="success" link size="small" @click="handleViewLessons(row)">
                课程
              </el-button>
              <el-popconfirm
                title="确定删除吗？"
                @confirm="handleDelete(row.id)"
              >
                <template #reference>
                  <el-button type="danger" link size="small">
                    删除
                  </el-button>
                </template>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
      </div>
        
      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="searchForm.page"
          v-model:page-size="searchForm.limit"
          :total="tagStore.pagination.total"
          :page-sizes="[20, 30, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handlePageChange"
          background
        />
      </div>
    </div>

    <!-- 简化的创建/编辑对话框 -->
    <el-dialog
      v-model="showCreateDialog"
      :title="editingTag ? '编辑标签' : '创建标签'"
      width="500px"
      :before-close="closeDialog"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="80px"
      >
        <el-form-item label="名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入标签名称" />
        </el-form-item>
        
        <el-form-item label="标识" prop="slug">
          <el-input v-model="form.slug" placeholder="请输入标签标识">
            <template #append>
              <el-button @click="generateSlug">生成</el-button>
            </template>
          </el-input>
        </el-form-item>
        
        <el-form-item label="描述">
          <el-input
            v-model="form.description"
            type="textarea"
            :rows="3"
            placeholder="请输入标签描述"
          />
        </el-form-item>
        
        <el-form-item label="颜色">
          <el-color-picker v-model="form.color" />
        </el-form-item>
        
        <el-form-item label="状态">
          <el-switch
            v-model="form.isActive"
            active-text="启用"
            inactive-text="禁用"
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="closeDialog">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="isSubmitting">
          {{ editingTag ? '更新' : '创建' }}
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useTagStore } from '@/stores/tag'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Plus,
  Search,
  Delete
} from '@element-plus/icons-vue'
import type { FormInstance, FormRules } from 'element-plus'
import type { Tag } from '@/types/admin'

const router = useRouter()
const tagStore = useTagStore()

const showCreateDialog = ref(false)
const editingTag = ref<Tag | null>(null)
const isSubmitting = ref(false)
const selectedIds = ref<number[]>([])

// 搜索表单
const searchForm = reactive({
  search: '',
  page: 1,
  limit: 20
})

// 标签表单
const formRef = ref<FormInstance>()
const form = reactive({
  name: '',
  slug: '',
  description: '',
  color: '#409EFF',
  isActive: true
})

// 表单验证规则
const rules: FormRules = {
  name: [
    { required: true, message: '请输入标签名称', trigger: 'blur' },
    { min: 2, max: 50, message: '标签名称长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  slug: [
    { required: true, message: '请输入标签标识', trigger: 'blur' },
    { pattern: /^[a-z0-9-]+$/, message: '标识只能包含小写字母、数字和连字符', trigger: 'blur' }
  ]
}

// 格式化日期
const formatDate = (date: string) => {
  if (!date) return '-'
  return new Date(date).toLocaleDateString()
}

// 处理搜索
const handleSearch = () => {
  searchForm.page = 1
  loadData()
}

// 加载数据
const loadData = () => {
  const params: any = {
    page: searchForm.page,
    limit: searchForm.limit
  }
  
  if (searchForm.search?.trim()) params.search = searchForm.search.trim()
  
  tagStore.fetchTags(params)
}

// 处理页码变化
const handlePageChange = (page: number) => {
  searchForm.page = page
  loadData()
}

// 处理每页数量变化
const handleSizeChange = (size: number) => {
  searchForm.limit = size
  searchForm.page = 1
  loadData()
}

// 处理选择变化
const handleSelectionChange = (selection: Tag[]) => {
  selectedIds.value = selection.map(item => item.id)
}

// 处理状态切换
const handleStatusChange = async (tag: Tag) => {
  try {
    await tagStore.toggleTagStatus(tag.id, tag.isActive)
  } catch (error) {
    tag.isActive = !tag.isActive
  }
}

// 打开创建对话框
const openCreateDialog = () => {
  showCreateDialog.value = true
}

// 编辑标签
const handleEdit = (tag: Tag) => {
  editingTag.value = tag
  Object.assign(form, {
    name: tag.name,
    slug: tag.slug,
    description: tag.description || '',
    color: tag.color || '#409EFF',
    isActive: tag.isActive
  })
  showCreateDialog.value = true
}

// 处理删除
const handleDelete = async (id: number) => {
  try {
    await tagStore.deleteTag(id)
    if (tagStore.tags.length === 1 && searchForm.page > 1) {
      searchForm.page -= 1
    }
    loadData()
  } catch (error) {
    // 错误已在store中处理
  }
}

// 处理批量删除
const handleBatchDelete = async () => {
  try {
    await ElMessageBox.confirm(
      `确定要删除选中的 ${selectedIds.value.length} 个标签吗？`,
      '批量删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const deleteCount = selectedIds.value.length
    await tagStore.deleteTagsBatch(selectedIds.value)
    selectedIds.value = []
    
    if (tagStore.tags.length <= deleteCount && searchForm.page > 1) {
      searchForm.page -= 1
    }
    loadData()
  } catch {
    // 用户取消
  }
}

// 查看标签下的课程
const handleViewLessons = (tag: Tag) => {
  router.push({
    name: 'AdminLessons',
    query: { tagId: tag.id }
  })
}

// 生成slug
const generateSlug = () => {
  if (!form.name) {
    ElMessage.warning('请先输入标签名称')
    return
  }
  
  form.slug = form.name
    .toLowerCase()
    .replace(/\s+/g, '-')
    .replace(/[^\w\-]/g, '')
}

// 关闭对话框
const closeDialog = () => {
  showCreateDialog.value = false
  editingTag.value = null
  formRef.value?.resetFields()
  Object.assign(form, {
    name: '',
    slug: '',
    description: '',
    color: '#409EFF',
    isActive: true
  })
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    isSubmitting.value = true
    
    if (editingTag.value) {
      await tagStore.updateTag(editingTag.value.id, form)
    } else {
      await tagStore.createTag(form)
    }
    
    closeDialog()
    loadData()
  } catch (error) {
    // 错误已在store中处理
  } finally {
    isSubmitting.value = false
  }
}

onMounted(() => {
  loadData()
})
</script>

<style scoped>
.tags-page {
  padding: 20px;
  background: #f5f5f5;
  min-height: 100vh;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 16px 20px;
  background: white;
  border-radius: 4px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.header-left h1 {
  margin: 0;
  font-size: 18px;
  font-weight: 500;
  color: #333;
}

.total-count {
  margin-left: 12px;
  color: #666;
  font-size: 14px;
}

.header-right {
  display: flex;
  align-items: center;
  gap: 16px;
}

.search-container {
  position: relative;
}

.search-input {
  width: 280px;
  transition: all 0.3s ease;
}

.search-input:focus-within {
  transform: scale(1.02);
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.15);
}

.search-input :deep(.el-input__wrapper) {
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
}

.search-input :deep(.el-input__wrapper):hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.search-icon {
  color: #909399;
  transition: color 0.3s ease;
}

.search-input:focus-within .search-icon {
  color: #409EFF;
}

.search-btn {
  border-radius: 0 6px 6px 0;
  border-left: 1px solid #dcdfe6;
  transition: all 0.3s ease;
}

.search-btn:hover {
  background: linear-gradient(135deg, #66b1ff, #409eff);
}

.add-btn {
  border-radius: 8px;
  padding: 12px 20px;
  font-weight: 600;
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.3);
  transition: all 0.3s ease;
}

.add-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.4);
}

.table-container {
  background: white;
  border-radius: 8px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.08);
  overflow: hidden;
  margin-bottom: 20px;
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 20px;
  background: linear-gradient(135deg, #fff3cd, #ffeaa7);
  border-bottom: 1px solid #f0c36d;
  animation: slideDown 0.3s ease;
}

@keyframes slideDown {
  from {
    opacity: 0;
    transform: translateY(-10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.table-title {
  display: flex;
  align-items: center;
  gap: 12px;
  font-size: 14px;
  font-weight: 600;
  color: #856404;
}

.table-actions {
  display: flex;
  align-items: center;
}

.batch-btn {
  background: linear-gradient(135deg, #ff6b6b, #ee5a52);
  border: none;
  border-radius: 6px;
  color: white;
  transition: all 0.3s ease;
}

.batch-btn:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(255, 107, 107, 0.4);
}

.table-wrapper {
  position: relative;
  overflow: hidden;
}

.data-table {
  border-radius: 0;
}

.data-table :deep(.el-table__header-wrapper) {
  background: #fafbfc;
}

.data-table :deep(.el-table__header th) {
  background: #fafbfc;
  color: #495057;
  font-weight: 600;
  border-bottom: 2px solid #dee2e6;
  padding: 12px 0;
}

.data-table :deep(.el-table__body-wrapper) {
  overflow-y: auto;
  scrollbar-width: thin;
  scrollbar-color: #c1c1c1 #f1f1f1;
}

.data-table :deep(.el-table__body-wrapper::-webkit-scrollbar) {
  width: 8px;
}

.data-table :deep(.el-table__body-wrapper::-webkit-scrollbar-track) {
  background: #f1f1f1;
  border-radius: 4px;
}

.data-table :deep(.el-table__body-wrapper::-webkit-scrollbar-thumb) {
  background: #c1c1c1;
  border-radius: 4px;
  transition: background 0.3s ease;
}

.data-table :deep(.el-table__body-wrapper::-webkit-scrollbar-thumb:hover) {
  background: #a8a8a8;
}

.data-table :deep(.el-table__row) {
  transition: all 0.2s ease;
}

.data-table :deep(.el-table__row:hover) {
  background: #f8f9fa;
  transform: scale(1.001);
}

.tag-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.tag-color {
  width: 16px;
  height: 16px;
  border-radius: 2px;
  flex-shrink: 0;
}

.tag-name {
  font-weight: 500;
  color: #333;
}

.tag-slug {
  font-size: 12px;
  color: #999;
}

.pagination {
  padding: 20px;
  text-align: right;
  background: #fafbfc;
  border-top: 1px solid #dee2e6;
}

.pagination :deep(.el-pagination) {
  gap: 8px;
}

.pagination :deep(.el-pager li) {
  border-radius: 6px;
  transition: all 0.2s ease;
}

.pagination :deep(.el-pager li:hover) {
  background: #409eff;
  color: white;
  transform: translateY(-1px);
}

.pagination :deep(.el-pagination__jump) {
  margin-left: 16px;
}

.pagination :deep(.el-select) {
  border-radius: 6px;
}

/* 表格样式重置 */
:deep(.el-table) {
  border: none;
}

:deep(.el-table th) {
  background: #fafafa;
  border-bottom: 1px solid #eee;
  font-weight: 500;
  color: #666;
}

:deep(.el-table td) {
  border-bottom: 1px solid #f5f5f5;
}

:deep(.el-table--striped .el-table__body tr.el-table__row--striped td) {
  background: #fafafa;
}

:deep(.el-table__body tr:hover td) {
  background: #f0f9ff;
}

/* 响应式 */
@media (max-width: 768px) {
  .tags-page {
    padding: 12px;
  }
  
  .page-header {
    flex-direction: column;
    gap: 12px;
  }
  
  .header-right {
    flex-direction: column;
    gap: 12px;
  }
  
  .header-right .el-input {
    width: 100% !important;
    margin-right: 0 !important;
  }
}
</style> 